<template>
  <div class="order-list">
    <h2>我的订单</h2>

    <el-tabs v-model="currentTab" @tab-click="handleTabClick">
      <el-tab-pane v-for="(tab, index) in tabs" :key="index" :label="tab.label" :name="index.toString()">
        <el-skeleton :rows="5" animated v-if="loading" />
        <div v-else-if="orders && orders.length > 0">
          <el-card v-for="order in orders" :key="order.id" class="order-card" shadow="hover" @click="showOrderDetails(order.id)">
            <template #header>
              <div class="card-header">
                <span>订单id: {{ order.id }}</span>
                <span>订单号: {{ order.orderId }}</span>
              </div>
            </template>
            <p>创建时间: {{ order.createTime }}</p>
            <p :style="getStatusStyle(order)">{{ getOrderStatus(order) }}</p>
            <p v-if="order.status === 0" style="color: red">
              {{ order.orderStatusMsg }}
            </p>
            <p v-if="order.status === 3 && order.refundStatus === 2" style="color: red">退款状态: {{order.orderStatus}}</p>
            <p>支付金额: {{ order.payPrice }} THB</p>
            <el-table :data="order.orderInfoList" stripe style="width: 100%">
              <el-table-column prop="productId" label="商品ID" width="180" />
              <el-table-column prop="num" label="数量" width="100" />
              <el-table-column prop="price" label="单价" width="100" />
              <el-table-column prop="allPrice" label="总价" width="100" />
            </el-table>
          </el-card>
        </div>
        <el-empty v-else description="暂无订单信息" />
      </el-tab-pane>

      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @total-change="handleTotalChange"
          :current-page="orderPagination.currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="orderPagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="orderPagination.total">
      </el-pagination>
    </el-tabs>

    <el-dialog v-model="dialogVisible" title="订单详情" width="50%">
      <el-descriptions v-if="currentOrder" :column="1" border>
        <el-descriptions-item label="订单ID">{{ currentOrder.id }}</el-descriptions-item>
        <el-descriptions-item label="订单号">{{ currentOrder.orderId }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentOrder.createTime }}</el-descriptions-item>
        <el-descriptions-item v-if="currentOrder.refundStatus === 0" label="状态">{{ currentOrder.paid === false ? "未支付" : "已支付" }}</el-descriptions-item>
        <el-descriptions-item v-else label="状态">{{ currentOrder.orderStatusMsg }}</el-descriptions-item>
        <el-descriptions-item label="支付金额">{{ currentOrder.payPrice }} THB</el-descriptions-item>
        <el-descriptions-item label="商品列表">
          <el-table :data="currentOrder.orderInfoList" stripe style="width: 100%">
            <el-table-column prop="productId" label="商品ID" width="180" />
            <el-table-column prop="num" label="数量" width="100" />
            <el-table-column prop="price" label="单价" width="100" />
            <el-table-column prop="allPrice" label="总价" width="100" />
          </el-table>
        </el-descriptions-item>
        <el-descriptions-item v-if="currentOrder && currentOrder.status === 0 && currentOrder.refundStatus === 0" label="支付期限">
          {{ currentOrder.orderStatusMsg }}
        </el-descriptions-item>
        <el-descriptions-item v-if="currentOrder && currentOrder.status === 0 && currentOrder.refundStatus === 0" label="支付倒计时">
          <p style="color: red;font-weight: bold;font-size: 16px">{{ getCountdown(currentOrder.orderStatusMsg) }}</p>
        </el-descriptions-item>
        <el-descriptions-item v-if="currentOrder && currentOrder.status === 1 && currentOrder.refundStatus === 4" label="申请理由">
            {{ currentOrder.refundReasonWap }}
        </el-descriptions-item>
        <el-descriptions-item v-if="currentOrder && currentOrder.status === 1 && currentOrder.refundStatus === 4" label="描述">
            {{ currentOrder.refundReasonWapExplain }}
        </el-descriptions-item>
        <el-descriptions-item v-if="currentOrder && currentOrder.status === 1 && currentOrder.refundStatus === 4" label="审核意见">
            <p style="color: red;font-weight: bold;font-size: 16px">{{ currentOrder.refundReason }}</p>
        </el-descriptions-item>
        <el-descriptions-item v-if="currentOrder && currentOrder.status === 1 && currentOrder.refundStatus === 1" label="申请理由">
            <p style="color: red;font-weight: bold;font-size: 16px">{{ currentOrder.refundReasonWap }}</p>
        </el-descriptions-item>
        <el-descriptions-item v-if="currentOrder && currentOrder.status === 1 && currentOrder.refundStatus === 1" label="描述">
            <p style="color: red;font-weight: bold;font-size: 16px">{{ currentOrder.refundReasonWapExplain }}</p>
        </el-descriptions-item>
      </el-descriptions>
      <div v-if="currentOrder" class="action-section">
        <div v-if="currentOrder.paid === false" class="payment-section">
          <el-button v-if="currentOrder.payId && currentOrder.status === 0" type="primary" @click="goToPayment">立即支付</el-button>
          <el-button v-else type="primary" @click="generatePayment" :loading="generatingPayment">生成支付链接</el-button>
          <el-button v-if="currentOrder.status === 0" type="success" @click="cancelOrder" :loading="cancellingOrder">取消订单</el-button>
        </div>
        <div v-if="currentOrder.paid === true" class="payment-section">
          <el-button v-if="currentOrder.status === 1 && currentOrder.refundStatus === 1" type="success" @click="cancelApplication" :loading="cancellingOrder">取消申请</el-button>
        </div>
        <el-button v-if="currentOrder.status === 1 && (currentOrder.refundStatus === 0 || currentOrder.refundStatus === 4)" type="success" @click="takeOrder" :loading="takingOrder">使用</el-button>
        <el-button v-if="currentOrder.status === 1 && (currentOrder.refundStatus === 0 || currentOrder.refundStatus === 4)" type="danger" @click="refundOrder(currentOrder)" :loading="refundingOrder">申请退款</el-button>
      </div>
    </el-dialog>

    <el-dialog v-model="refundDialogVisible" title="申请退款">
      <el-form :model="refundForm">
        <el-form-item label="退款理由" :label-width="formLabelWidth">
          <el-input v-model="refundForm.text" type="textarea" :rows="3"></el-input>
        </el-form-item>
        <el-form-item label="描述(可选)" :label-width="formLabelWidth">
          <el-input v-model="refundForm.explain" type="textarea" :rows="3"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="refundDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRefundOrder">确认</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {computed, onMounted, onUnmounted, ref,nextTick } from 'vue';
import {useStore} from 'vuex';
import {ElMessage} from 'element-plus';

const store = useStore();

const currentTab = ref('0');
const loading = ref(false);
const dialogVisible = ref(false);
const currentOrder = ref(null);
const generatingPayment = ref(false);
const cancellingOrder = ref(false);
const takingOrder = ref(false);
const refundingOrder = ref(false);
const refundDialogVisible = ref(false);
const formLabelWidth = '120px'
const refundForm = ref({
  text: '',
  id: null,
  explain:'',
  uni:''
})
const ordersType = ref(0)
const tabs = [
  { label: '未支付', type: 0 },
  { label: '待使用', type: 1 },
  { label: '已完成', type: 2 },
  { label: '已取消', type: 3 },
  { label: '退款审核中', type: -1 },
  { label: '退款中', type: -2 },
  { label: '已退款', type: -3 },
];

const orders = computed(() => store.getters['fetchOrders/getOrders']);
const orderPagination = computed(() => ({
  currentPage: store.state.fetchOrders.orderPagination.currentPage,
  pageSize: store.state.fetchOrders.orderPagination.pageSize,
  total: store.state.fetchOrders.orderPagination.total
}))
// 处理订单分页变化
const handleSizeChange = async (val) => {
  try {
    await store.commit('fetchOrders/SET_ORDER_PAGE_SIZE', val)
    await store.commit('fetchOrders/SET_TYPE', tabs[ordersType.value].type)
    await store.dispatch('fetchOrders/fetchOrders')
  } catch (error) {
    ElMessage.error('更改页面大小失败')
  }
}

const handleCurrentChange = async (val) => {
  try {
    await store.commit('fetchOrders/SET_ORDER_CURRENT_PAGE', val )
    await store.commit('fetchOrders/SET_TYPE', tabs[ordersType.value].type)
    await store.dispatch('fetchOrders/fetchOrders')
  } catch (error) {
    ElMessage.error('更改页码失败')
  }
}

const handleTotalChange = async (val) => {
  try {
    await store.commit('fetchOrders/SET_ORDER_TOTAL', val )
    await store.commit('fetchOrders/SET_TYPE', tabs[ordersType.value].type)
    await store.dispatch('fetchOrders/fetchOrders')
  } catch (error) {
    ElMessage.error('更改数量失败')
  }
}

const fetchOrders = async () => {
  loading.value = true;
  try {
    await store.dispatch('fetchOrders/fetchOrders');
  } catch (error) {
    ElMessage.error('获取订单失败');
  } finally {
    loading.value = false;
  }
};

const getOrderStatus = (order) => {
  const { status, refundStatus, orderStatus } = order;
  if (status === 1 && refundStatus === 4) return '状态: 待使用';
  if (status === 2 && [0, 4].includes(refundStatus)) return '状态: 已完成';
  if (status === 3 && [0, 2].includes(refundStatus)) return '状态: 已取消';
  if (status === 2 && refundStatus === 4) return `退款状态: ${orderStatus}`;
  return `状态: ${orderStatus}`;
};

const getStatusStyle = () => {
  return {
    color: 'red',
    fontWeight: 'bold',
    fontSize: '16px',
    display: 'block'
  };
};

const handleTabClick = async (tab) => {
  ordersType.value = parseInt(tab.paneName);
  await store.commit('fetchOrders/SET_TYPE', tabs[ordersType.value].type);
  await store.dispatch('fetchOrders/fetchOrders');
};

const showOrderDetails = async (orderId) => {
  try {
    currentOrder.value = await store.dispatch('fetchOrderDetails/fetchOrderDetails', orderId);
    dialogVisible.value = true;
  } catch (error) {
    ElMessage.error(error.message);
  }
};

const goToPayment = () => {
  if (currentOrder.value && currentOrder.value.payId) {
    window.open(`https://www.sandbox.paypal.com/checkoutnow?token=${currentOrder.value.payId}`, '_self');
  }
};

const generatePayment = async () => {
  if (!currentOrder.value) return;

  cancellingOrder.value = true;
  generatingPayment.value = true;

  try {
    const result = await store.dispatch('createPayPalOrder/createPayPalOrder', {
      orderNo: currentOrder.value.orderId,
      uni: currentOrder.value.id,
    });

    if (result.success) {
      currentOrder.value.payId = result.orderNo;
      await nextTick(); // 等待 Vue 更新 DOM
      console.log('PayPal Order No:', result.orderNo);
      console.log('Current Order payId:', currentOrder.value.payId);
      ElMessage.success('支付链接生成成功，请点击"立即支付"按钮进行支付');
    } else {
      throw new Error(result.error);
    }
  } catch (error) {
    console.error('生成支付链接失败:', error);
    ElMessage.error(error.message || '生成支付链接失败，请稍后重试');
  } finally {
    generatingPayment.value = false;
    cancellingOrder.value = false;
  }
};

const cancelOrder = async () => {
  if (!currentOrder.value) return;

  cancellingOrder.value = true;
  generatingPayment.value = true;
  try {
    await store.dispatch('cancelOrder/cancelOrder', currentOrder.value.id);
    ElMessage.success('订单取消成功');
    dialogVisible.value = false;
    // 重新获取当前标签页的订单列表
    await fetchOrders(parseInt(currentTab.value));
  } catch (error) {
    ElMessage.error(error.message || '取消订单失败，请稍后重试');
  } finally {
    cancellingOrder.value = false;
    generatingPayment.value = false;
  }
};

const cancelApplication = async () => {
  if (!currentOrder.value) return;

  cancellingOrder.value = true;
  generatingPayment.value = true;
  try {
    await store.dispatch('cancelOrder/cancelApplication', currentOrder.value.id);
    ElMessage.success('取消申请成功');
    dialogVisible.value = false;
    // 重新获取当前标签页的订单列表
    await fetchOrders(parseInt(currentTab.value));
  } catch (error) {
    ElMessage.error(error.message || '取消申请失败，请稍后重试');
  } finally {
    cancellingOrder.value = false;
    generatingPayment.value = false;
  }
};

const takeOrder = async () => {
  if (!currentOrder.value) return;

  takingOrder.value = true;
  refundingOrder.value = true;
  try {
    await store.dispatch('takeOrder/takeOrder', currentOrder.value.id);
    ElMessage.success('订单消费成功');
    dialogVisible.value = false;
    // 重新获取当前标签页的订单列表
    await fetchOrders(parseInt(currentTab.value));
  } catch (error) {
    ElMessage.error(error.message || '消费失败，请稍后重试');
  } finally {
    takingOrder.value = false;
    refundingOrder.value = false;
  }
};

const refundOrder = (order) => {
  currentOrder.value = order
  refundForm.value.id = order.id
  refundForm.value.uni = order.orderId
  refundDialogVisible.value = true
}

const confirmRefundOrder = async () => {
  if (!currentOrder.value) return;

  takingOrder.value = true;
  refundingOrder.value = true;
  try {
    await store.dispatch('refundOrder/refundOrder', { ...refundForm.value });
    ElMessage.success('申请退款成功');
    refundDialogVisible.value = false;
    dialogVisible.value = false;
    // 重新获取当前标签页的订单列表
    await fetchOrders(parseInt(currentTab.value));
  } catch (error) {
    ElMessage.error(error.message || '退款失败，请稍后重试');
  } finally {
    takingOrder.value = false;
    refundingOrder.value = false;
  }
};

const getCountdown = (orderStatusMsg) => {
  const deadlineMatch = orderStatusMsg.match(/(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/);
  if (!deadlineMatch) return "无法计算倒计时";

  const deadline = new Date(deadlineMatch[1]);
  const now = new Date();
  const timeDiff = deadline - now;

  if (timeDiff <= 0) {
    return "已过期";
  }

  const hours = Math.floor(timeDiff / (1000 * 60 * 60));
  const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((timeDiff % (1000 * 60)) / 1000);

  return `${hours}小时 ${minutes}分钟 ${seconds}秒`;
};

const timer = ref(null);

const updateCountdowns = () => {
  // 强制组件重新渲染
  if (currentOrder.value) {
    currentOrder.value = { ...currentOrder.value };
  }
};


onMounted(() => {
  fetchOrders(0);
  // 每秒更新一次倒计时
  timer.value = setInterval(updateCountdowns, 1000);
});

// 在组件卸载时清除定时器
onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value);
  }
});
</script>

<style scoped>
.action-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 10px;
}
.payment-section {
  margin-top: 20px;
  text-align: center;
}
.order-list {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.order-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.order-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
